package com.qfedu.department.service.impl;

import java.util.UUID;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.qfedu.common.entity.WoPage;
import com.qfedu.common.util.WoUtil;
import com.qfedu.department.dto.DepartmentDto;
import com.qfedu.psys.dto.WoUser;
import com.qfedu.department.po.Department;
import com.qfedu.department.repository.DepartmentRepository;
import com.qfedu.department.service.DepartmentService;

/**
 * PO实体Department对应的Service接口实现类.
 * @author cailei
 */
@Service
@Transactional
public class DepartmentServiceImpl implements DepartmentService {

	/**
	 * 使用日志打印框架.
	 */
	private final static Logger LOG = LogManager.getLogger(DepartmentServiceImpl.class);
	
	/**
	 * 注入DepartmentRepository.
	 */
	@Resource // @Autowired
	private DepartmentRepository departmentRepository;

	/**
	 * 列表
	 * @param currentUser 当前用户
	 * @param searchContent 查询内容文本
	 * @param page 页索引,从1开始
	 * @param size 一页的最大记录数
	 * @return
	 */
	@Override
	public WoPage<DepartmentDto> getPageData(WoUser currentUser, String searchContent, Long page, Long size) {
		// 从dao获取数据
		Pageable pageInput = PageRequest.of(page.intValue() - 1, size.intValue());
		Page<Department> pageData = null;
		if (WoUtil.isEmpty(searchContent)) {
			pageData = departmentRepository.findAll(pageInput);
		} else {
			pageData = departmentRepository.findAllByNameLike("%" + searchContent + "%", pageInput);
		}
		// 将Department转化为DepartmentDto
		WoPage<DepartmentDto> pr = DepartmentDto.getPageData(pageData.getContent(), pageData.getTotalElements());
		return pr.setPage(page);
	}

	/**
	 * 创建
	 * @param currentUser 当前用户
	 * @param dto 
	 */
	@Override
	public void create(WoUser currentUser, DepartmentDto dto) {
		Department po = dto.createPO();
		departmentRepository.save(po);
	}

	/**
	 * 根据id获取对象
	 * @param id
	 * @return
	 */
	@Override
	public DepartmentDto getById(String id) {
		Department po = departmentRepository.findById(id).get();
		return new DepartmentDto(po);
	}

	/**
	 * 更新对象
	 * @param dto
	 */
	@Override
	public void update(DepartmentDto dto) {
		Department po = departmentRepository.findById(dto.getId()).get();
		dto.updatePO(po);
		departmentRepository.save(po);
	}

	/**
	 * 根据ids值删除多个对象
	 * @param ids
	 */
	@Override
	public void delete(String[] ids) {
		for (String id : ids) {
			departmentRepository.deleteById(id);
		}
	}

}
